package cn.forge.mall.framework.core.util;

import cn.forge.mall.framework.common.pojo.PageParam;
import cn.forge.mall.framework.common.pojo.SortingField;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liangyuanping
 * @ClassName MybatisUtils
 * @description:
 * @date 2024年03月19日
 * @version: 1.0
 */
public class MybatisUtils {

    public static <T> Page<T> buildPage(PageParam pageParam, Collection<SortingField> sortingFields) {
        //设置页码和每页大小
        Page<T> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        // 排序字段
        if (!CollectionUtils.isEmpty(sortingFields)) {
            List<OrderItem> orderItems = sortingFields.stream().map(sortingField -> SortingField.ORDER_ASC.equals(sortingField.getOrder()) ?
                    OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField())).collect(Collectors.toList());
            page.addOrder(orderItems);
        }
        return page;
    }
}
